package com.sy.live.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

public class HttpUtil
{
	private static Logger logger = Logger.getLogger(HttpUtil.class);
	private static HttpClient httpClient = new HttpClient();
	
	/**
	 * 通过GET方法获得网页内容
	 * @param uri	网页地址
	 * @return
	 */
	public static String getResponseBodyByGetMethod(String uri)
	{
		GetMethod getMethod = new GetMethod(uri);
		
		//网页内容
		String content = "";
		
		try
		{
			if((httpClient.executeMethod(getMethod) == HttpStatus.SC_OK))
			{
				content = getMethod.getResponseBodyAsString();
				logger.info("获取网页内容成功.");
			}else
			{
				logger.info("获取网页内容失败.");
			}
		} catch (Exception e)
		{
			logger.info("获得网页内容出错.");
			e.printStackTrace();
		} finally
		{
			//释放HTTP链接
			getMethod.releaseConnection();
		}
		
		return content;
	}
	
	/**
	 * 通过GET方法获得网页内容
	 * @param uri	网页地址
	 * @param encoding 页面编码
	 * @return
	 */
	public static String getResponseBodyByGetMethod(String uri, String encoding)
	{
		GetMethod getMethod = new GetMethod(uri);
		
		//网页内容
		String content = "";
		
		try
		{
			if((httpClient.executeMethod(getMethod) == HttpStatus.SC_OK))
			{
				BufferedReader br = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream(), encoding));
				
				String t = null;
				
				while((t = br.readLine()) != null)
				{
					content += t + "\n";
				}
				
				br.close();
				
				logger.info("获取网页内容成功.");
			}else
			{
				logger.info("获取网页内容失败.");
			}
		} catch (Exception e)
		{
			logger.info("获得网页内容出错.");
			e.printStackTrace();
		} finally
		{
			//释放HTTP链接
			getMethod.releaseConnection();
		}
		
		return content;
	}
}
